#!/bin/sh
# 作者: Unknown chen_eric@126.com
# 描述：主要为一些非云原生的代码做启动前配置，和gosu切换到普通用户启动代码；
#		比如一些代码配置文件还需要配置本机IP，可以通过-e sed ''去实现；
#		/${RUNONCE_PATH}下可以放一些脚本(注: _runonce.sh结尾只会运行一次)，这样就不需要init容器了;
#		脚本很简单，其它功能查看脚本即可。
# 
# Version: 1.0.2
# ChangLog：
#   2020-08-02: New
#   2020-08-11: Add run pre script
#   2021-08-04: Add runonce
#   2021-10-15: alpine version

set -eo pipefail
RUN_AS_USER=unknown
RUNONCE_PATH="/unknownprescripts"
RUNONCE_CHECK_PATH="/.unknownrunonce"

for i in ${RUNONCE_PATH}/*.sh; do
    if [ ! -e "${RUNONCE_CHECK_PATH}${i}" -a -r "$i" ]; then
        . "$i" &> /dev/null
        [[ $i =~ _runonce.sh$ ]] && mkdir -p ${RUNONCE_CHECK_PATH}${i}
    fi
done

while getopts 'u:f:e:' OPT; do
	case $OPT in
		u)	
			set +e
			id $OPTARG &> /dev/null
			if [[ $? -ne 0 ]];then
				set -e
				if [ "$(id -u)" != "0" ]; then
					echo "[WARNING] The current user is not root and $OPTARG is not exist, so the run_as_user is ${RUN_AS_USER}"
				else
					adduser -D ${RUN_AS_USER}
					RUN_AS_USER=$OPTARG
				fi
			else
				RUN_AS_USER=$OPTARG
			fi
			;;
		f)
			for i in $(echo $OPTARG | tr ',' ' ');do
				mkdir -p $i
				set +eo pipefail
				chown -R $RUN_AS_USER:$RUN_AS_USER $i &> /dev/null
				set -eo pipefail
			done
			;;
		e)
			eval $OPTARG
			;;

		?)
			echo "Usage: `basename $0` [-u RUNNASUSER] [-f FOLDER1,FOLDER2] [-e EVAL_COMMAND] COMMAND"
			exit 1
	esac
done
shift $(($OPTIND - 1))
if [[ "$RUN_AS_USER" == "root" && "$(id -u)" == "0" ]]; then
	exec "$@"
else
	exec /opt/gosu $RUN_AS_USER "$@"
fi
